<template>
  <base-breadcrumb :breadcrumb="!isAudit">
    <!-- <div> -->
      <a-spin :spinning="loading.detailLoading">
    <a-card>
      <a-steps
        :current="1"
        direction="vertical"
      >
        <a-step title="第一步">
          <span slot="description">
            <template>
              <div class="table-page-search-wrapper">
                <title-name title="基本信息" />
                <a-form-model
                  ref="basicForm"
                  :model="queryParam"
                  :rules="basicRules"
                  hide-required-mark
                >
                  <a-row :gutter="24">
                    <a-col
                      :md="16"
                      :sm="16"
                    >
                      <a-form-model-item
                        label="所属单位"
                        :label-col="{ lg: { span: 5 }, sm: { span: 5 } }"
                        :wrapper-col="{ lg: { span: 17 }, sm: { span: 17 } }"
                        prop="projectId"
                      >
                        <org-tree-select
                          v-model="queryParam.projectId"
                          is-need-auth
                          is-auto-select-first
                          check-strictly
                          disabled
                          @select="selectOrg"
                        />
                      </a-form-model-item>
                    </a-col>
                    <!--                    <a-col-->
                    <!--                      :md="8"-->
                    <!--                      :sm="8"-->
                    <!--                    >-->
                    <!--                      <a-form-model-item-->
                    <!--                        label="所属分公司"-->
                    <!--                        :label-col="{ lg: { span: 5 }, sm: { span: 5 } }"-->
                    <!--                        :wrapper-col="{ lg: { span: 17 }, sm: { span: 17 } }"-->
                    <!--                        prop="branchComId"-->
                    <!--                      >-->
                    <!--                        <SelectSubCompany-->
                    <!--                          v-model="queryParam.branchComId"-->
                    <!--                          placeholder="请选择"-->
                    <!--                          :disabled="!editable"-->
                    <!--                        />-->
                    <!--                      </a-form-model-item>-->
                    <!--                    </a-col>-->
                    <!--                    <a-col-->
                    <!--                      :md="8"-->
                    <!--                      :sm="8"-->
                    <!--                    >-->
                    <!--                      <a-form-model-item-->
                    <!--                        label="所属项目"-->
                    <!--                        :label-col="{ lg: { span: 5 }, sm: { span: 5 } }"-->
                    <!--                        :wrapper-col="{ lg: { span: 17 }, sm: { span: 17 } }"-->
                    <!--                        prop="projectId"-->
                    <!--                      >-->
                    <!--                        <SelectProject-->
                    <!--                          ref="selectProject"-->
                    <!--                          v-model="queryParam.projectId"-->
                    <!--                          placeholder="请选择"-->
                    <!--                          :disabled="!editable"-->
                    <!--                          key-value="branchComId"-->
                    <!--                          :form="queryParam"-->
                    <!--                          :clear-list="true"-->
                    <!--                          @selectChange="handleProChanged"-->
                    <!--                        />-->
                    <!--                      </a-form-model-item>-->
                    <!--                    </a-col>-->
                    <!-- <a-col :md="12" :sm="12">
                                            <a-form-model-item
                                                label="年度"
                                                :labelCol="{ lg: { span: 5 }, sm: { span: 5 } }"
                                                :wrapperCol="{ lg: { span: 17 }, sm: { span: 17 } }"
                                                prop="year"
                                            >
                                                <a-date-picker
                                                    format="YYYY"
                                                    mode="year"
                                                    :value="queryParam.year"
                                                    :open="open"
                                                    @openChange="openChange"
                                                    @panelChange="panelChange"
                                                    placeholder="请选择"
                                                    :disabled="!editable"
                                                />
                                            </a-form-model-item>
                                        </a-col> -->
                    <a-col
                      :md="8"
                      :sm="8"
                    >
                      <a-form-model-item
                        label="名称"
                        :label-col="{ lg: { span: 5 }, sm: { span: 5 } }"
                        :wrapper-col="{ lg: { span: 17 }, sm: { span: 17 } }"
                        prop="constructionName"
                      >
                        <BaseInput
                          v-model="queryParam.constructionName"
                          placeholder=""
                          disabled
                        />
                      </a-form-model-item>
                    </a-col>
                    <a-col
                      :md="24"
                      :sm="24"
                    >
                      <a-form-model-item
                        label="项目地点"
                        :label-col="{ lg: { span: 5 }, sm: { span: 5 } }"
                        :wrapper-col="{ lg: { span: 17 }, sm: { span: 17 } }"
                      >
                        <BaseTextarea
                          v-model="queryParam.projectVenue"
                          placeholder=""
                          disabled
                        />
                      </a-form-model-item>
                    </a-col>

                    <a-col
                      :md="24"
                      :sm="24"
                    >
                      <a-form-model-item
                        label="项目概况"
                        :label-col="{ lg: { span: 5 }, sm: { span: 5 } }"
                        :wrapper-col="{ lg: { span: 17 }, sm: { span: 17 } }"
                      >
                        <BaseTextarea
                          v-model="queryParam.projectOverview"
                          :rows="4"
                          disabled
                        />
                      </a-form-model-item>
                    </a-col>
                  </a-row>
                </a-form-model>
              </div>
            </template>
          </span>
        </a-step>
        <a-step title="第二步">
          <span
            v-if="id || basicId"
            slot="description"
          >
            <!-- <span  slot="description"> -->
            <a-card
              :bordered="false"
              style="box-shadow: 0 0 0;"
            >
              <div class="title-version">
                <title-name title="施组(方案)审批计划表" />
              <div class="change-version" v-if="$route.query.type == 'change'" >
                  <label class="mr10p">版本：</label>
                  <a-select 
                    v-model="currentVersion"
                    style="width: 100px"
                    @select="changeVersion"
                    :disabled="$route.query.type == 'change' || editable"
                  >
                    <a-select-option
                      v-for="(item, index) in versionData"
                      :key="index"
                      :value="item.value"
                    >
                      {{ item.label }}
                    </a-select-option>
                  </a-select>
                </div>
              </div>
              <a-form-model
                  ref="basicForm"
                  :model="queryParam"
                  :rules="changeRules"
                  hide-required-mark
                  v-if="$route.query.type == 'change' || queryParam.changeReason"
                >
               <!-- 变更时候显示，或者是查看时，有原因也显示 -->
                <a-row :gutter="24">
                  <a-col :md="24" :sm="24">
                    <a-form-model-item label="变更原因" :label-col="{ lg: { span: 5 }, sm: { span: 5 } }" :wrapper-col="{ lg: { span: 17 }, sm: { span: 17 } }" prop="changeReason">
                        <BaseTextarea v-model="queryParam.changeReason" :rows="4" :disabled="$route.query.type == 'view' || isAudit"/>
                    </a-form-model-item>
                  </a-col>
                  <a-col :md="24" :sm="24">
                    <a-form-model-item label="附件上传" :label-col="{ lg: { span: 5 }, sm: { span: 5 } }" :wrapper-col="{ lg: { span: 17 }, sm: { span: 17 } }" prop="fileInfoVOList">
                            <upload-list  :businessCode="'TM01'" :uploadArrys.sync="queryParam.fileInfoVOList"  @fileArrysData="handleFileUploaded" multiple  :disabled="$route.query.type == 'view' || isAudit"></upload-list>
                            <p v-if="$route.query.type != 'view'">提示：请上传变更理由证明文件</p>
                        </a-form-model-item>
                    </a-col>
                </a-row>
              </a-form-model>
              <div
                class="table-operator"
                style="display: flex;justify-content: space-between;"
              >
                <div>
                  <a-button
                    v-if="editable || $route.query.type == 'change'"
                    type="primary"
                    @click="addPlan"
                  >添加计划项</a-button>
                </div>
                <div v-if="$route.query.type != 'change'">
                  <!-- :disabled="editable || $route.query.type == 'change'" -->
                  <label  class="mr10p">版本：</label>
                  <a-select
                    v-model="currentVersion"
                    style="width: 100px"
                    @select="changeVersion"
                    :disabled="$route.query.type == 'change' || editable"
                  >
                    <a-select-option
                      v-for="(item, index) in versionData"
                      :key="index"
                      :value="item.value"
                    >
                      {{ item.label }}
                    </a-select-option>
                  </a-select>
                </div>
              </div>
              <!-- :scroll="{ x: 1500}" -->
              <!-- 不是查看时候显示 -->
              <a-table
                :data-source="dataSource"
                v-if="type != 'view'"
                :columns="columns"
                bordered
                row-key="id"
                style="margin-top:10px"
              >
                <span
                  slot="description"
                  slot-scope="text"
                >
                  <ellipsis
                    :length="8"
                    tooltip
                  >{{ text }}</ellipsis>
                </span>
                <!-- <span slot="changeReason"  slot-scope="text, record, index">
                  <BaseTextarea v-model="record.changeReason" :rows="4"/>
                </span> -->
                <span
                  slot="serial"
                  slot-scope="text, record, index"
                >{{ index + 1 }}</span>
                <!-- 操作 -->
                <span
                  v-if="type != 'view'"
                  slot="operation"
                  slot-scope="text, record,index"
                >
                  <template>
                    <a
                      :disabled="record.quote"
                      @click="addSee(record)"
                    >编辑</a>
                    <a-divider type="vertical" />
                    <a
                      :disabled="record.quote"
                      @click="deletePlan(record,index)"
                    >删除</a>
                  </template>
                </span>
              </a-table>
              <Scheme style="margin-top:10px" :reqObj="reqObj" v-if="type == 'view' && reqObj.businessVersion" ></Scheme>
            </a-card>
          </span>
        </a-step>
      </a-steps>
    </a-card>
    <div v-if="!isConsultation" class="page-btn-right-top" style="display: flex;">
      <!-- <div style="display: flex; float: right"> -->
      <template v-if="(id || basicId)">
        <!-- <a-button
          v-if="(id || basicId) && queryParam.auditStatus == 'DRAFT'"
          class="ml12"
          type="danger"
          :disabled="!editable"
          @click="discard(queryParam)"
        >
          删除草稿
        </a-button> -->
        <a-button
          v-if="((id || basicId) && editable) || changeable"
          :loading="loading.isDraft"
          class="ml12"
          type="primary"
          :disabled="!editable && !changeable"
          @click="beforeSub((changeable || queryParam.auditStatus=='DRAFT_CHANGE') ? '4' : '0')"
        >
          保存草稿
        </a-button>
        <a-button
          v-if="((id || basicId) && editable) || changeable"
          :loading="loading.isSaving"
          class="ml12"
          type="primary"
          :disabled="!editable && !changeable"
          @click="beforeSub((changeable || queryParam.auditStatus=='DRAFT_CHANGE') ? '5' : '1')"
        >
          提交
        </a-button>
      </template>
      <template v-else>
        <a-button
          :loading="loading.isNexting"
          type="primary"
          :disabled="!editable || hasPlan"
          @click="save"
        >
          下一步
        </a-button>
      </template>
      <BasePrintButton
        v-if="type == 'view' && !isAudit"
        type="primary"
        :before-print-fn="print"
      />
      <a-button
        class="ml12"
        type="primary"
        @click="handleClose"
      >
        关闭
      </a-button>
    </div>
    </a-spin>
    <!-- </div> -->
    <a-modal
      title="施组(方案)审批计划项管理"
      :visible="planvisible"
      :width="1010"
      :confirm-loading="loading.savePlan"
      @cancel="cancel"
      @ok="submitPlan(tableData)"
    >
      <a-form-model
        ref="form"
        :model="tableData"
        :rules="rules"
        hide-required-mark
      >
        <a-row :gutter="24">
          <a-col
            :md="12"
            :sm="12"
          >
            <a-form-model-item
              label="施组(方案)名称"
              :label-col="{ lg: { span: 5 }, sm: { span: 5 } }"
              :wrapper-col="{ lg: { span: 17 }, sm: { span: 17 } }"
              prop="schemeName"
            >
              <BaseInput v-model="tableData.schemeName" />
            </a-form-model-item>
          </a-col>
          <a-col
            :md="12"
            :sm="12"
          >
            <a-form-model-item
              label="方案类型"
              :label-col="{ lg: { span: 5 }, sm: { span: 5 } }"
              :wrapper-col="{ lg: { span: 17 }, sm: { span: 17 } }"
              prop="schemeCategoryId"
            >
              <a-select
                v-model="tableData.schemeCategoryId"
                placeholder="请选择"
                @select="handleChange"
              >
                <a-select-option
                  v-for="item in option"
                  :key="item.id"
                  :value="item.id"
                >
                  {{
                    item.name
                  }}
                </a-select-option>
              </a-select>
            </a-form-model-item>
          </a-col>
          <a-col
            :md="12"
            :sm="12"
          >
            <a-form-model-item
              label="计划编制人"
              :label-col="{ lg: { span: 5 }, sm: { span: 5 } }"
              :wrapper-col="{ lg: { span: 17 }, sm: { span: 17 } }"
              prop="preparedUserId"
            >
            <ASelectOrgPeople v-model="tableData.preparedUserId" :orgId="SelectOrgId" :init="false" @onSelectChange="aSelectOrgPeopleFn"></ASelectOrgPeople>
            </a-form-model-item>
          </a-col>
          <a-col
            :md="12"
            :sm="12"
          >
            <a-form-model-item
              label="计划报审时间"
              :label-col="{ lg: { span: 5 }, sm: { span: 5 } }"
              :wrapper-col="{ lg: { span: 17 }, sm: { span: 17 } }"
              prop="planReviewTime"
            >
              <a-date-picker
                v-model="tableData.planReviewTime"
                style="width: 100%"
                @change="changeplanReviewTime"
              />
            </a-form-model-item>
          </a-col>
          <a-col
            :md="12"
            :sm="12"
          >
            <a-form-model-item
              label="要求审批完成时间"
              :label-col="{ lg: { span: 7 }, sm: { span: 7 } }"
              :wrapper-col="{ lg: { span: 15 }, sm: { span: 15 } }"
              prop="reviewEndTime"
            >
              <a-date-picker
                v-model="tableData.reviewEndTime"
                style="width: 100%"
                @change="changereviewEndTime"
              />
            </a-form-model-item>
          </a-col>
          <a-col
            :md="24"
            :sm="24"
          >
            <a-form-model-item
              label="其他审批需求"
              :label-col="{ lg: { span: 5 }, sm: { span: 5 } }"
              :wrapper-col="{ lg: { span: 17 }, sm: { span: 17 } }"
              prop="reviewOtherRequirements"
            >
              <BaseTextarea
                v-model="tableData.reviewOtherRequirements"
                :rows="4"
              />
            </a-form-model-item>
            <a-form-model-item v-if="isShowChangeDetailReason && $route.query.type == 'change'"
              label="变更原因"
              :label-col="{ lg: { span: 5 }, sm: { span: 5 } }"
              :wrapper-col="{ lg: { span: 17 }, sm: { span: 17 } }"
              prop="changeDetailReason"
            >
              <BaseTextarea
                v-model="tableData.changeDetailReason"
                :rows="4"
              />
            </a-form-model-item>
          </a-col>
        </a-row>
      </a-form-model>
    </a-modal>
    <selectApprover :businessId="businessId"  :processConfig="setProcessConfig"></selectApprover>
  </base-breadcrumb>
</template>


<script>
import BaseTextarea from '@/components/BaseTextarea'
import { getProjectsDel } from '@/api/project/projects'
import SelectSubCompany from '@/components/Select/SelectSubCompany' // 分公司
import SelectProject from '@/components/Select/SelectProject' // 项目
import BasePrintButton from '@/components/BasePrintButton' // 打印按钮
import ASelectOrgPeople from '@/components/Select/ASelectOrgPeople'
import UploadList from '@/components/UploadList'
import Scheme from './scheme'
import moment from 'moment'
import {
    addList,
    editList,
    deleteList,
    getPlanList,
    addPlanList,
    editPlanList,
    deletePlanList,
    getDetails,
    listOption,
    getVersionList,
    canAdd,
    hasDetail,
    printPlan,
} from '@/api/technical/approvalPlan'
import { checkVisibleInDetail } from '@/utils/util'
import { Item } from 'ant-design-vue/es/vc-menu'
import { clone } from 'lodash'
import cloneDeep from 'lodash.clonedeep' // 深拷贝
const columns = [
    {
        title: '序号',
        width: '80px',
        scopedSlots: { customRender: 'serial' },
    },
    {
        title: '施组(方案)名称',
        dataIndex: 'schemeName',
    },
    {
        title: '方案类别',
        width: '80px',
        dataIndex: 'schemeCategory',
    },
    {
      title: '计划编制人',
      dataIndex: 'preparedUserName',
    },
    {
        title: '计划报审时间',
        dataIndex: 'planReviewTime',
    },
    {
        title: '要求审批完成时间',
        dataIndex: 'reviewEndTime',
    },
    {
        title: '审批其他需求',
        dataIndex: 'reviewOtherRequirements',
        width: '300px',
    },
    {
      title: '状态',
      width: '120px',
      dataIndex: 'approvalManagementStatusStr',
    },
    {
      title: '变更原因',
      dataIndex: 'changeDetailReason',
      scopedSlots: { customRender: 'changeDetailReason' },
      width: '200px',
    },
    {
        title: '操作',
        dataIndex: 'operation',
        width: '120px',
        scopedSlots: { customRender: 'operation' },
    },
]
export default {
    name:'a'+Date.now(),
    components: {
        SelectSubCompany,
        SelectProject,
        BaseTextarea,
        BasePrintButton,
        ASelectOrgPeople,
        UploadList,
        Scheme
    },
    data() {
        const validReviewTime = (rule, value, callback) => {
            const { planReviewTime, reviewEndTime } = this.tableData
            if (planReviewTime && reviewEndTime) {
                const start = new Date(planReviewTime).getTime()
                const end = new Date(reviewEndTime).getTime()
                if (start > end) {
                    callback(new Error('审批完成时间不能小于计划报审时间'))
                }
            }
            callback()
        }
        // this.columns = columns
        return {
            columns,
            // checkVisibleInDetail1: checkVisibleInDetail(this),
            loading: {
                isNexting: false,
                isSaving: false,
                savePlan: false,
                isDraft: false,
                detailLoading: false,
            },
            queryParam: { constructionName: '',fileInfoVOList:[]},
            basicRules: {
                branchComId: [{ required: true, message: '请选择', trigger: 'change' }],
                projectId: [{ required: true, message: '请选择', trigger: 'change' }],
                year: [{ required: true, message: '请选择', trigger: 'change' }],
            },
            //变更校验
            changeRules:{
              changeReason: [{ required: true, message: '请输入', trigger: 'change' }],
              //fileInfoVOList:[{ required: true, message: '请上传附件', trigger: 'change' }],
            },
            visible: false,
            planvisible: false,
            form: {},
            option: [],
            type: '',
            disabled: false,
            planId: '',
            basicId: '',
            dataSource: [],
            id: '',
            open: false, //年份弹框
            rules: {
                schemeName: [{ required: true, message: '请输入', trigger: 'change' }],
                schemeCategoryId: [{ required: true, message: '请选择', trigger: 'change' }],
                preparedUserId: [{ required: true, message: '请选择', trigger: 'change' }],
                planReviewTime: [
                    { required: true, message: '请选择', trigger: 'change' },
                    { validator: validReviewTime, trigger: 'change' },
                ],
                reviewEndTime: [
                    { required: true, message: '请选择', trigger: 'change' },
                    { validator: validReviewTime, trigger: 'change' },
                ],
                changeDetailReason: [{ required: true, message: '请输入', trigger: 'change' }],
                // reviewOtherRequirements: [{ required: true, message: '请输入', trigger: 'change' }],
            },
            hasPlan: false,
            currentVersion: 'V1.0',
            versionData: [
              // { label: 'V1.0', value: '1'},
              // { label: 'V2.0', value: '2'}
            ],
            //获取流程配置值
            processConfig: null,
            //点击提交发送流程配置值
            setProcessConfig: null,
            businessId: null,
            SelectOrgId:null,   //单位id
            reqObj:{
              planId:'',
              businessVersion:null,
            }, //查看时施组(方案)审批计划表table请求参数
            tableData:{}, //施组(方案)审批计划详情数据
            isShowChangeDetailReason:false, //是否需要显示变更原因
            cacheLine:{},  //缓存行的数据
            deleteIdList:[], //删除table id
        }
    },
    props: {
      // 是否作为审批详情
      isAudit: {
        type: Boolean,
        default: false
      },
      // 是否作为意见征询
      isConsultation: {
        type: Boolean,
        default: false
      }
    },

    watch: {
      tableData: {
            deep:true,
            handler(val) {
               if(!this.diff(val,this.cacheLine) || val.changeDetailReason){   //缓存行数据和变化的数据不相等就显示,或者有变更原因就显示
                 this.isShowChangeDetailReason = true;
               }else{
                this.isShowChangeDetailReason = false;
               }
            },
        },
        isAudit: {
            immediate: true,
            handler(val) {
                if (val) {
                    this.$nextTick(() => {
                        this.type = 'view'
                    })
                }
            },
        },
    },
    computed: {
      changeable() {
        return this.$route.query.type == 'change'
      },
      editable() {
        return this.$route.query.type == 'add' || this.$route.query.type == 'edit'
      }
    },
   async mounted() {
         //获取通过获取流程配置值
    this.processConfig = await this.$getConfigFn('technology_construction_planmanage');

    },
    created() {
        this.id = this.$route.query.id
        this.type = this.$route.query.type
        // this.getPlanList()

        // status==1 查看
        const status = (this.type == 'edit' || this.type == 'change') ? 0 : 1
        getVersionList({id: this.id, status}).then((res) => {
          if (res.code == 200) {
            this.versionData = res.data.map((v) => {
              return {
                label: v,
                value: v
              }
            })
            this.currentVersion = res.data[res.data.length -1]
            this.reqObj.planId = this.id;
            this.reqObj.businessVersion = this.currentVersion;
            this.getDetails()
          }
        }).catch(() => {
          this.getDetails()
        })
        if(!this.changeable && this.type == 'edit'){   //不是变更删除变更原因,并且是编辑
         let newColumns= cloneDeep(this.columns);
          newColumns.splice(8,1);
          this.columns = newColumns;
      }
    },
    methods: {
      diff(obj1, obj2) {
        var o1 = obj1 instanceof Object;
        var o2 = obj2 instanceof Object;
        // 判断是不是对象
        if (!o1 || !o2) {
          return obj1 === obj2;
        }

        //Object.keys() 返回一个由对象的自身可枚举属性(key值)组成的数组,
        //例如：数组返回下表：let arr = ["a", "b", "c"];console.log(Object.keys(arr))->0,1,2;
        if (Object.keys(obj1).length !== Object.keys(obj2).length) {
          return false;
        }

        for (var o in obj1) { // 遍历对象 fon in 循环 o 为 对象的属性名  
          var t1 = obj1[o] instanceof Object;
          var t2 = obj2[o] instanceof Object;
          if (t1 && t2) {
            return diff(obj1[o], obj2[o]);
          } else if (obj1[o] !== obj2[o]) {
            console.log('false')
            return false;
          }
        }
        return true;
   },
      handleFileUploaded(list) {
            this.queryParam.fileInfoVOList = [...list]
        },
        //选择计划编制人
    aSelectOrgPeopleFn(data){
      this.tableData.preparedUserName = data?.name;
    },
      selectOrg(val) {
        console.log('valvalvalvalvalvalval',val)
        this.queryParam.branchComId = val[val.length - 2].orgId
        this.SelectOrgId = val[val.length - 1].orgId
        const data = {
          name: val[val.length - 1].projectName,
          code: this.queryParam.projectId
        }
      },
        // handleProChanged() {

        // },
        // 删除草稿
        discard(e) {
            let that = this
            that.$confirm({
                title: '温馨提示',
                content: '确定是否删除数据？',
                okText: '确认',
                okType: 'danger',
                cancelText: '取消',
                onOk() {
                    return deleteList({ id: e.id })
                        .then((res) => {
                            that.$message.success('删除成功！')
                            that.handleClose()
                        })
                        .catch((res) => {
                            that.$message.warning('删除失败！')
                        })
                },
            })
        },
        // openChange(status) {
        //     if (status) {
        //         this.open = true
        //     } else {
        //         this.open = false
        //     }
        // },
        // panelChange(value) {
        //     this.queryParam.year = value
        //     this.open = false;
        //     this.queryParam.constructionName = this.queryParam.year+'施组方案审批计划'
        // },

        async getProjectDetail(id) {
            if (!id) return
            const res = await getProjectsDel({
                projectId: id,
            })
            if (res.data.code === 200 || res.code === 200) {
                const { projectAddress, projectFeatures } = res.data
                this.queryParam = {
                    ...this.queryParam,
                    projectVenue: projectAddress,
                    projectOverview: projectFeatures,
                }
            } else {
                this.queryParam = {
                    ...this.queryParam,
                    projectVenue: '',
                    projectOverview: '',
                }
            }
        },
        handleClose() {
            if (this.isAudit) {
                window.close()
            } else {
                this.$multiTab.close(this.$route.fullpath)
            }
        },
        handleChange(name) {
          let findData =  this.option.find((item)=>item.id == name);
          this.tableData.schemeCategory = findData?.name;
        },
        changeVersion() {
          this.getDetails()
          this.reqObj.businessVersion = this.currentVersion;
        },
        getDetails() {
            if (this.id) {
                const status = (this.type == 'edit' || this.type == 'change') ? 0 : 1
                const param = {
                  id: this.id,
                  version: this.currentVersion,
                  status
                }
                this.loading.detailLoading = true
                getDetails(param).then((res) => {
                    const data = res.data.approvalPlan || {}
                    const data2 = res.data.approvalPlanChangeReason || {}
                    this.queryParam = { ...data,...data2}
                    this.dataSource = res.data.implementationPlanEdit || []
                    if(!this.queryParam.constructionName){  //名称不存在就要拼接
                      this.queryParam.constructionName = `${this.queryParam.projectName}项目施组（方案）审批计划`;
                    }
                    this.$nextTick(() => {
                        this.queryParam.projectId = data.projectId
                        this.getProjectDetail(data.projectId)
                    })
                    this.loading.detailLoading = false
                })
            }
        },
        listOption() {
            listOption({ type: '5' }).then((res) => {
                this.option = res.data
            })
        },
        deletePlan(record,index) {
            let that = this
            that.$confirm({
                title: '温馨提示',
                content: '确定是否删除数据？',
                okText: '确认',
                okType: 'danger',
                cancelText: '取消',
                onOk() {
                  if(record.tableId){
                    const index = that.dataSource.findIndex((item) => item.tableId === record.tableId)
                    index > -1 && that.dataSource.splice(index, 1);
                    that.deleteIdList.push( record.tableId);
                    // return deletePlanList({ id: record.tableId })
                    //     .then((res) => {
                    //         that.$message.success('删除成功！')
                    //         const index = that.dataSource.findIndex((item) => item.tableId === record.tableId)
                    //         index > -1 && that.dataSource.splice(index, 1);
                    //         that.deleteIdList.push( record.tableId);
                    //     })
                    //     .catch((res) => {
                    //         that.$message.warning('删除失败！')
                    //     })
                  }else{
                    let index =  that.dataSource.findIndex((item)=>item.sort == record.sort)
                    that.dataSource.splice(index,1);  
                  }
               
                },
            })
        },
        addPlan() {
            this.tableData = {}
            this.planId = ''
            this.planvisible = true
            this.listOption()
            this.tableData.businessVersion = this.currentVersion;
            if(this.changeable){   //变更
              this.isShowChangeDetailReason = true;
            }
        },
        cancel() {
            this.planvisible = false
            this.$refs.form.resetFields()
            this.isShowChangeDetailReason = false;
        },
        addSee(record) {
            this.listOption()
            this.planvisible = true
            this.planId = record.id;
            this.isShowChangeDetailReason = false;
            this.cacheLine = {}
            if(this.changeable){
               this.cacheLine = cloneDeep(record);
            }
            this.tableData = { ...record }
        },
        handleOk() {},
        getPlanList() {
            getPlanList().then((res) => {
                this.dataSource = res.data
            })
        },
        changereviewEndTime(value, dateString) {
            this.tableData.reviewEndTime = dateString
        },
        changeplanReviewTime(value, dateString) {
            this.tableData.planReviewTime = dateString
        },
        submitPlan(data) {
            this.$refs.form.validate((valid) => {
                if (!valid) {
                  this.$message.warning("请填写完所有必填项信息")
                  return
                }
                if (this.loading.savePlan) return
                //this.loading.savePlan = true
                // if (this.id) {
                //     this.form.id = this.id
                // } else {
                //     this.form.id = this.basicId
                // }c
                if(data.id){    //就是编辑
                // 有sort说明是前端数据，有id则为后端数据
                if (data.sort) {
                    let index =  this.dataSource.findIndex((item)=>item.sort == data.sort)
                    this.dataSource.splice(index, 1, data)
                } else if (data.id) {
                  let sort = this.dataSource.findIndex((i) => i.id === data.id)
                  this.dataSource[sort] = data
                  //this.dataSource.splice(sort - 1, 1, data)
                }
                }else{
                  if(data.sort){
                    let index =  this.dataSource.findIndex((item)=>item.sort == data.sort)
                    this.dataSource.splice(index, 1, data)
                  }else{
                    data.sort = Math.random(); //用随机数
                    this.dataSource.unshift(data);
                  }
                }
              this.planvisible = false
              // console.log(this.form,this.planId,data)
              // if(this.planId){
              //   let findIndexData = this.dataSource.findIndex((item)=>item.id == this.form.id);  //前端赋值
              //   console.log(findIndexData,1222)
              //   this.dataSource[findIndexData] = this.form
              // }else{
                
              // }
                // if (this.planId) {
                //     editPlanList(this.form)
                //         .then((res) => {
                //             this.loading.savePlan = false
                //             if (res.code == '200') {
                //                 this.$message.success('修改成功')
                //                 this.planvisible = false
                //                 this.getDetails()
                //             }
                //         })
                //         .catch(() => {
                //             this.loading.savePlan = false
                //         })
                // } else {
                //     addPlanList(this.form)
                //         .then((res) => {
                //             this.loading.savePlan = false
                //             if (res.code === 200 || res.data.code === 200) {
                //                 this.$message.success('新增成功')
                //                 this.planvisible = false
                //                 this.getDetails()
                //             }
                //         })
                //         .catch(() => {
                //             this.loading.savePlan = false
                //         })
                // }
            })
        },
        save() {
            this.$refs.basicForm.validate((valid) => {
                if (!valid) {
                  this.$message.warning("请填写完所有必填项信息")
                  return
                }
                if (this.loading.isNexting) return
                this.loading.isNexting = true
                this.queryParam.auditStatus = '0'
                this.loading.detailLoading = true;
                this.queryParam.businessVersion = this.currentVersion;
                if (this.id) {
                    this.queryParam.id = this.id
                    this.queryParam.deleteIdList = this.deleteIdList;
                    editList(this.queryParam)
                        .then((res) => {
                            this.loading.isNexting = false
                            this.loading.detailLoading = false;
                            if (res.code == '200' || res.data.code === 200) {
                                this.visible = true
                                this.$message.success('成功')
                                return hasDetail(res.data.id)
                            }
                        })
                        .then((res) => {
                          if (res.data.code == 200 && res.data.message) {
                            this.getDetails()
                          }
                        })
                        .catch(() => {
                            this.loading.isNexting = false
                        })
                } else {
                    addList(this.queryParam)
                        .then((res) => {
                            this.loading.isNexting = false
                              this.loading.detailLoading = false;
                            this.basicId = res.data.id
                            this.id = res.data.id
                            if (res.code == '200' || res.data.code === 200) {
                                this.visible = true
                                this.$message.success('成功')
                                return hasDetail(res.data.id)
                            }
                        })
                        .then((res) => {
                          if (res.data.code == 200 && res.data.message) {
                            this.getDetails()
                          }
                        })
                        .catch(() => {
                            this.loading.isNexting = false
                        })
                }
            })
        },
        beforeSub(auditStatus) {
          let that = this
          that.setProcessConfig = null;
          console.log(this.dataSource,'queryParam')
          const msg = (auditStatus == '1' || auditStatus == '5') ? '提交' : '保存草稿'
          if (auditStatus == '1' || auditStatus == '5') {
              this.submit(auditStatus)
            // that.$confirm({
            //     title: '温馨提示',
            //     content: `确定${msg}吗？`,
            //     okText: '确认',
            //     cancelText: '取消',
            //     onOk() {
            //       return that.submit(auditStatus)
            //     }
            // })
          } else {
            this.submit(auditStatus)
          }
        },
        submit(auditStatus) {
          return new Promise((resolve, rej) => {
            this.$refs.basicForm.validate((valid) => {
                if (!valid) {
                  this.$message.warning("请填写完所有必填项信息")
                  return
                }
                if(this.changeable && (!this.queryParam.fileInfoVOList || !this.queryParam.fileInfoVOList.length)){
                  this.$message.warning("请上传附件")
                  return

                }
                // if (this.loading.isSaving) return
                (auditStatus == '1' || auditStatus == '5') ? (this.loading.isSaving = true) : (this.loading.isDraft = true)
                this.queryParam.auditStatus = auditStatus
                this.submitApprovalConfirm((auditStatus == '1' || auditStatus == '5')?this.processConfig:6,(flag)=>{
                  if(!flag) {
                      this.loading.isSaving = false
                    return
                  }
                  this.loading.detailLoading = true;
                  this.queryParam.businessVersion = this.currentVersion;
                  if (this.id) {
                    this.queryParam.id = this.id
                    this.queryParam.detailsDto = this.dataSource
                    this.queryParam.deleteIdList = this.deleteIdList;
                    editList(this.queryParam)
                        .then((res) => {
                            this.loading.isSaving = false
                            this.loading.detailLoading = false;
                            if (res.code == '200' || res.data.code === 200) {
                                this.visible = true
                                this.$message.success('成功')
                                 //提交时，返回id
                                 if (auditStatus == '1' || auditStatus == '5'){
                                  this.businessId = res.data.id;
                                  this.setProcessConfig = this.processConfig;
                                  }else {
                                    this.handleClose()
                                  }
                                //this.handleClose()
                                resolve()
                            }
                        })
                        .catch(() => {
                            this.loading.isSaving = false
                            reject()
                        })
                } else {
                  this.loading.detailLoading = true;
                    addList(this.queryParam)
                        .then((res) => {
                            this.loading.isSaving = false
                            this.loading.detailLoading = false;
                            this.basicId = res.data.id
                            if (res.code == '200' || res.data.code === 200) {
                                this.visible = true
                                this.$message.success('成功')
                                //提交时，返回id
                                if (auditStatus == '1' || auditStatus == '5'){
                                  this.businessId = res.data.id;
                                 this.setProcessConfig = this.processConfig;
                                }else {
                                  this.handleClose()
                                }
                                //this.handleClose()
                                resolve()
                            }
                        })
                        .catch(() => {
                            this.loading.isSaving = false
                            reject()
                        })
                }
                })
            })
          })
        },
        print() {
          const param = {
            id: this.$route.query.id,
            version: this.currentVersion
          }
          return printPlan(param).then((res) => {
            return res.data.content
          })
        },
    },
}
</script>
<style scoped>
.steps-content {
    margin-top: 16px;
    border: 1px dashed #e9e9e9;
    border-radius: 6px;
    background-color: #fafafa;
    min-height: 200px;
    text-align: center;
    padding-top: 80px;
}

.steps-action {
    margin-top: 24px;
}
.button {
    margin: 10px;
}
.title-version{
  display: flex;
  justify-content:space-between
}
</style>
